﻿using Google.Protobuf.Collections;
using log4net;
using Newtonsoft.Json;
using StoreProject.BLL;
using StoreProject.BLL.SettingBLL;
using StoreProject.DAL;
using StoreProject.Entity;
using StoreProject.Forms.SettingForms;
using StoreProject.Forms.WorkingProcedure;
using StoreProject.OtherUtil;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StoreProject.Forms
{
    public partial class CreeateOrderForm : Form
    {
        ILog _log = LogManager.GetLogger("CreeateOrderForm");
        WorkingProcedureBLL workingProcedureBLL = new WorkingProcedureBLL();
        OrderBLL _orderBll = new OrderBLL();
        CustomerBLL customerBLL = new CustomerBLL();
        LineTypeBLL lineTypeBLL = new LineTypeBLL();
        ChangefulBLL changefulBLL = new ChangefulBLL();
        OperatorBLL operatorBLL = new OperatorBLL();
        public CreeateOrderForm()
        {
            InitializeComponent();
        }

        private void CreeateOrderForm_Load(object sender, EventArgs e)
        {
            try
            {
                cmbProcessFlow.DisplayMember = "ProcessFlowName";
                cmbProcessFlow.ValueMember = "Id";

                var list = _orderBll.GetList().OrderByDescending(x => x.OrderId).Take(100).ToList().Select(x => x.OrderId).ToArray();
                //this.cmbOrderId.Items.AddRange(list);
                this.cmbOrderId.DataSource = list;
                InitData();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
        }


        public string GetLastBatchNo()
        {
            var changeEntity = changefulBLL.GetList().ToList();
            if (changeEntity != null && changeEntity.Count == 1)
            {
                int batchNo = changeEntity[0].BatchNo + 1;
                this.txtBatch.Text = "Lv" + batchNo;
                if (this.txtBatch.Text.Length < 8)
                {
                    string temp = "Lv";
                    int sum = 8 - this.txtBatch.Text.Length;
                    for (int i = 0; i < sum; i++)
                    {
                        temp += "0";
                    }
                    temp += batchNo;
                    this.txtBatch.Text = temp;
                    return temp;
                }
            }
            return null;
        }
        public void InitData()
        {
            this.txtBatch.Text = GetLastBatchNo();

            //工序数据源配置
            List<ProcessFlow> list = new List<ProcessFlow>();
            var groupList = workingProcedureBLL.GetListEx().GroupBy(x => x.ProcessFlowId);
            foreach (var group in groupList)
            {
                ProcessFlow processFlow = new ProcessFlow();
                processFlow.Id = group.Key;
                string temp = "";
                foreach (var item in group.ToList().OrderBy(x => x.IndexNum))
                {
                    temp += (item.IndexName + "+");
                }
                if (!string.IsNullOrEmpty(temp))
                    temp = temp.Remove(temp.Length - 1, 1);
                processFlow.ProcessFlowName = temp;
                list.Add(processFlow);
            }
            cmbProcessFlow.DataSource = list;

            //客户数据源配置
            var customer = customerBLL.GetList().Select(x => x.CustomerName).ToList();
            customer.Insert(0, "");
            cmbCustomer.DataSource = customer;

            //线型数据源配置
            var linetype = lineTypeBLL.GetList().Select(x => x.LineTypeName).ToList();
            linetype.Insert(0, "");
            cmbLineType.DataSource = linetype;

            //操作员数据源配置
            var operatorEx = operatorBLL.GetList().Select(x => x.OperatorName).ToList();
            operatorEx.Insert(0, "");
            cmbOperator.DataSource = operatorEx;
        }
        public bool IsValid()
        {
            errorProvider1.Clear();
            bool res = true;

            if (string.IsNullOrEmpty(txtOrder.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(txtOrder, "制令单号不能为空！");
            }
            else if (string.IsNullOrEmpty(txtFinishedProductName.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(txtFinishedProductName, "成品名称不能为空！");
            }
            else if (string.IsNullOrEmpty(txtSemiFinishedProductName.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(txtSemiFinishedProductName, "半成品名称不能为空！");
            }
            else if (string.IsNullOrEmpty(txtBatch.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(txtBatch, "批号不能为空！");
            }
            else if (string.IsNullOrEmpty(numPlanNum.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(numPlanNum, "计划数量不能为空！");
            }
            else if (cmbProcessFlow.SelectedItem as ProcessFlow == null)
            {
                res = false;
                errorProvider1.SetError(cmbProcessFlow, "工序不能为空！");
            }
            else if (string.IsNullOrEmpty(cmbLineType.Text))
            {
                res = false;
                errorProvider1.SetError(cmbLineType, "线型不能为空！");
            }
            else if (string.IsNullOrEmpty(cmbCustomer.Text))
            {
                res = false;
                errorProvider1.SetError(cmbCustomer, "客户不能为空！");
            }
            else if (string.IsNullOrEmpty(cmbDomesticAndExportSales.Text))
            {
                res = false;
                errorProvider1.SetError(cmbDomesticAndExportSales, "内外销不能为空！");
            }
            return res;
        }

        private void btnCreateOrder_Click(object sender, EventArgs e)
        {
            try
            {
               
                if (!IsValid())
                    return;
                var list = _orderBll.GetListByWhere(txtOrder.Text).ToList();
                if (list != null && list.Count > 0)
                {
                    MessageBox.Show("该制令单号已存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                var entity = GetEntity();
                var newBanchNo = GetLastBatchNo();
                if (newBanchNo != entity.Batch)
                {
                    MessageBox.Show("批号已在别处更新!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ClearControl();
                    return;
                }
                _log.Info("开始创建制令单：");
                _log.Info(string.Format("创建的制令单的基础数据为：{0}", JsonConvert.SerializeObject(entity)));
                var flag = _orderBll.Insert(entity);
                if (flag)
                {
                    _log.Info("创建制令单成功");
                    var changeEntity = changefulBLL.GetList().ToList();
                    if (changeEntity != null && changeEntity.Count == 1)
                    {
                        var entityEx = changeEntity[0];
                        _log.Info(string.Format("更新前的批号为：{0}",entityEx.BatchNo));
                        entityEx.BatchNo = entityEx.BatchNo + 1;
                        var flag1 = changefulBLL.Update(entityEx);
                        if (flag1)
                        {
                            var newchangeEntity = changefulBLL.GetList().ToList();
                            _log.Info(string.Format("更新后的批号为：{0}", newchangeEntity[0].BatchNo));
                        }
                    }
                    MessageBox.Show("新增成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    var listnew = _orderBll.GetList().OrderByDescending(x => x.OrderId).Take(100).ToList().Select(x => x.OrderId).ToArray();
                    //this.cmbOrderId.Items.AddRange(list);
                    this.cmbOrderId.DataSource = listnew;
                }
                else
                {
                    MessageBox.Show("新增失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                //this.Close();
                ClearControl();
            }
            catch (Exception ex)
            {
                _log.Info(ex.Message);
            }
            
        }

        public void ClearControl()
        {
            this.txtOrder.Text = string.Empty;
            txtFinishedProductName.Text = string.Empty;
            txtSemiFinishedProductName.Text = "#";
            numPlanNum.Value = 1;
            dateTimeRequestedDate.Value = DateTime.Now;
            txtJuanNum.Text = string.Empty;
            txtDanZhong.Text = string.Empty;
            cmbLineType.SelectedIndex = 0;
            cmbCustomer.SelectedIndex = 0;
            cmbDomesticAndExportSales.SelectedIndex = 0;
            cmbOperator.SelectedIndex = 0;
            InitData();
        }
        public OrderEntity GetEntity()
        {
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.Id = Guid.NewGuid().ToString();
            orderEntity.OrderId = txtOrder.Text;
            orderEntity.Batch = txtBatch.Text;
            orderEntity.Operator = cmbOperator.Text;
            orderEntity.Customer = cmbCustomer.Text;
            orderEntity.FinishedProductName = txtFinishedProductName.Text;
            orderEntity.DomesticAndExportSales = cmbDomesticAndExportSales.Text;
            orderEntity.CreateTime = DateTime.Now;
            orderEntity.LineType = cmbLineType.Text;
            orderEntity.PlanNums = Convert.ToInt32(numPlanNum.Value);
            orderEntity.RequestedDate = dateTimeRequestedDate.Value;
            orderEntity.UpdateTime = DateTime.Now;
            orderEntity.SemiFinishedProductName = txtSemiFinishedProductName.Text;
            orderEntity.JuanNum = txtJuanNum.Text;
            orderEntity.DanZhong = txtDanZhong.Text;
            var item = cmbProcessFlow.SelectedItem as ProcessFlow;
            if (item != null)
                orderEntity.ProcessFlowId = item.Id;//
            return orderEntity;
        }
        private void numPlanNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
                e.Handled = true;
        }

        private void cmbOrderId_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //ChangeValue();
            }
        }
        public void ChangeValue()
        {
            if (!string.IsNullOrEmpty(txtOrder.Text))
            {
                var list = _orderBll.GetListByWhere(txtOrder.Text).ToList();
                if (list == null || list.Count < 1)
                {
                    MessageBox.Show("该制令单号不存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                OrderEntity orderEntity = new OrderEntity();
                orderEntity = list[0];
                //this.txtBatch.Text = orderEntity.Batch;
                this.txtFinishedProductName.Text = orderEntity.FinishedProductName;
                this.numPlanNum.Value = orderEntity.PlanNums;
                this.txtSemiFinishedProductName.Text = orderEntity.SemiFinishedProductName;
                this.cmbLineType.Text = orderEntity.LineType;
                this.cmbCustomer.Text = orderEntity.Customer;
                this.dateTimeRequestedDate.Value = orderEntity.RequestedDate;
                this.txtJuanNum.Text = orderEntity.JuanNum;
                this.txtDanZhong.Text = orderEntity.DanZhong;
                this.cmbOperator.Text = orderEntity.Operator;
                this.cmbDomesticAndExportSales.Text = orderEntity.DomesticAndExportSales;
                var temp = workingProcedureBLL.GetListByStatus(orderEntity.ProcessFlowId).ToList()[0];
                this.cmbProcessFlow.SelectedValue = temp.ProcessFlowId;
            }
        }

        private void txtFinishedProductName_Leave(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.txtFinishedProductName.Text))
                    return;
                var list = _orderBll.GetListEx(this.txtFinishedProductName.Text).Select(x => x.ProcessFlowId).Distinct().ToList();
                if (list != null && list.Count > 0)
                {
                    List<ProcessFlow> datasource = new List<ProcessFlow>();
                    foreach (var item in list)
                    {
                        var entity = workingProcedureBLL.GetListByStatus(item).FirstOrDefault();
                        if (entity == null || entity.IsDeleted == true)
                            continue;
                        ProcessFlow processFlow = new ProcessFlow();
                        processFlow.Id = item;
                        string temp = "";
                        var groupList = workingProcedureBLL.GetListByStatus(item);
                        foreach (var item1 in groupList.OrderBy(x => x.IndexNum))
                        {
                            temp += (item1.IndexName + "+");
                        }
                        if (!string.IsNullOrEmpty(temp))
                            temp = temp.Remove(temp.Length - 1, 1);
                        processFlow.ProcessFlowName = temp;
                        datasource.Add(processFlow);
                    }

                    List<ProcessFlow> pList = (List<ProcessFlow>)cmbProcessFlow.DataSource;
                    if (pList != null && pList.Count > 0)
                    {
                        List<ProcessFlow> tempList = new List<ProcessFlow>();
                        foreach (var item in pList)
                        {
                            if (!datasource.Exists(x => x.Id == item.Id))
                            {
                                tempList.Add(item);
                            }
                        }
                        datasource.AddRange(tempList);
                        cmbProcessFlow.DataSource = datasource;
                    }
                }
            }
            catch (Exception ex)
            { }
        }

        private void cmbOrderId_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void cmbOrderId_SelectedValueChanged(object sender, EventArgs e)
        {
            string temp = this.cmbOrderId.Text.Substring(0, this.cmbOrderId.Text.Length - 2);
            txtOrder.Text = temp;
        }
    }
}
